package com.n.passwordbook.MainWindow;

import com.n.passwordbook.PasswordBook.PasswordBook;
import com.n.passwordbook.Utils.CryptographyHelper;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;

import java.util.function.Consumer;

public class CustomTextFieldTableCell<T> extends TableCell<T, String>
{

    private TextField txt_showText;
    private String oldStr;

    public static Consumer<Boolean> functionOnCommit;

    public CustomTextFieldTableCell()
    {
    }

    @Override
    public void startEdit()
    {
        if (!isEmpty())
        {
            super.startEdit();
            oldStr = getString();
            createTextField();
            setText(null);
            setGraphic(txt_showText);
            txt_showText.selectAll();
        }
    }

    @Override
    public void cancelEdit()
    {
        super.cancelEdit();
        setText(getItem());
        setGraphic(null);
    }

    @Override
    public void updateItem(String item, boolean empty)
    {
        super.updateItem(item, empty);

        if (empty)
        {
            setText(null);
            setGraphic(null);
        }
        else
        {
            if (isEditing())
            {
                if (txt_showText != null)
                {
                    txt_showText.setText(getString());
                }
                setText(null);
                setGraphic(txt_showText);
            }
            else
            {
                setText(getString());
                setGraphic(null);
            }
        }
    }

    private void createTextField()
    {
        txt_showText = new TextField(CryptographyHelper.decryptStringByAES256(oldStr, PasswordBook.PBKey));
        txt_showText.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        txt_showText.setOnAction(e -> {
            if (txt_showText.getText().equals(oldStr))
            {
                cancelEdit();
            }
            else
            {
                commitEdit(CryptographyHelper.encryptStringByAES256(txt_showText.getText(), PasswordBook.PBKey));
                functionOnCommit.accept(false);
            }
        });
    }

    private String getString()
    {
        return getItem() == null ? "" : getItem().toString();
    }
}

